home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / fw_perl.idb / usr / freeware / catman / u_man / cat1 / perlfaq4.Z / perlfaq4
Encoding:
Text File  |  1998-10-28  |  74.4 KB  |  1,981 lines

  1.  
  2.  
  3.  
  4.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  5.  
  6.  
  7.  
  8.      NNNNAAAAMMMMEEEE
  9.       perlfaq4 - Data Manipulation ($Revision: 1.26    $, $Date:
  10.       1998/08/05 12:04:00 $)
  11.  
  12.      DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  13.       The section of the FAQ answers question related to the
  14.       manipulation of data as numbers, dates, strings, arrays,
  15.       hashes, and miscellaneous data issues.
  16.  
  17.      DDDDaaaattttaaaa:::: NNNNuuuummmmbbbbeeeerrrrssss
  18.       WWWWhhhhyyyy aaaammmm IIII ggggeeeettttttttiiiinnnngggg lllloooonnnngggg    ddddeeeecccciiiimmmmaaaallllssss ((((eeeegggg,,,, 11119999....9999444499999999999999999999999999999999999999999999))))
  19.       iiiinnnnsssstttteeeeaaaadddd ooooffff tttthhhheeee nnnnuuuummmmbbbbeeeerrrrssss IIII sssshhhhoooouuuulllldddd bbbbeeee ggggeeeettttttttiiiinnnngggg ((((eeeegggg,,,, 11119999....99995555))))????
  20.  
  21.       The infinite set that    a mathematician    thinks of as the real
  22.       numbers can only be approximate on a computer, since the
  23.       computer only    has a finite number of bits to store an
  24.       infinite number of, um, numbers.
  25.  
  26.       Internally, your computer represents floating-point numbers
  27.       in binary.  Floating-point numbers read in from a file or
  28.       appearing as literals    in your    program    are converted from
  29.       their    decimal    floating-point representation (eg, 19.95) to
  30.       the internal binary representation.
  31.  
  32.       However, 19.95 can't be precisely represented    as a binary
  33.       floating-point number, just like 1/3 can't be    exactly
  34.       represented as a decimal floating-point number.  The
  35.       computer's binary representation of 19.95, therefore,    isn't
  36.       exactly 19.95.
  37.  
  38.       When a floating-point    number gets printed, the binary
  39.       floating-point representation    is converted back to decimal.
  40.       These    decimal    numbers    are displayed in either    the format you
  41.       specify with _p_r_i_n_t_f(), or the    current    output format for
  42.       numbers (see the section on $# in the    _p_e_r_l_v_a_r    manpage    if you
  43.       use print.  $# has a different default value in Perl5    than
  44.       it did in Perl4.  Changing $#    yourself is deprecated.
  45.  
  46.       This affects aaaallllllll computer languages that represent decimal
  47.       floating-point numbers in binary, not    just Perl.  Perl
  48.       provides arbitrary-precision decimal numbers with the
  49.       Math::BigFloat module    (part of the standard Perl
  50.       distribution), but mathematical operations are consequently
  51.       slower.
  52.  
  53.       To get rid of    the superfluous    digits,    just use a format (eg,
  54.       printf("%.2f", 19.95)) to get    the required precision.     See
  55.       the section on _F_l_o_a_t_i_n_g-_p_o_i_n_t    _A_r_i_t_h_m_e_t_i_c in the _p_e_r_l_o_p
  56.       manpage.
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.      Page 1                        (printed 10/23/98)
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  71.  
  72.  
  73.  
  74.       WWWWhhhhyyyy iiiissssnnnn''''tttt mmmmyyyy ooooccccttttaaaallll ddddaaaattttaaaa iiiinnnntttteeeerrrrpppprrrreeeetttteeeedddd ccccoooorrrrrrrreeeeccccttttllllyyyy????
  75.  
  76.       Perl only understands    octal and hex numbers as such when
  77.       they occur as    literals in your program.  If they are read in
  78.       from somewhere and assigned, no automatic conversion takes
  79.       place.  You must explicitly use _o_c_t()    or _h_e_x() if you    want
  80.       the values converted.     _o_c_t() interprets both hex ("0x350")
  81.       numbers and octal ones ("0350" or even without the leading
  82.       "0", like "377"), while _h_e_x()    only converts hexadecimal
  83.       ones,    with or    without    a leading "0x",    like "0x255", "3A",
  84.       "ff",    or "deadbeef".
  85.  
  86.       This problem shows up    most often when    people try using
  87.       _c_h_m_o_d(), _m_k_d_i_r(), _u_m_a_s_k(), or    _s_y_s_o_p_e_n(), which all want
  88.       permissions in octal.
  89.  
  90.           chmod(644,  $file); # WRONG -- perl -w catches this
  91.           chmod(0644, $file); # right
  92.  
  93.  
  94.       DDDDooooeeeessss ppppeeeerrrrllll hhhhaaaavvvveeee aaaa rrrroooouuuunnnndddd ffffuuuunnnnccccttttiiiioooonnnn????  WWWWhhhhaaaatttt aaaabbbboooouuuutttt _c_e_i_l() and
  95.       _f_l_o_o_r()?  Trig functions?
  96.  
  97.       Remember that    _i_n_t() merely truncates toward 0.  For rounding
  98.       to a certain number of digits, _s_p_r_i_n_t_f() or _p_r_i_n_t_f() is
  99.       usually the easiest route.
  100.  
  101.           printf("%.3f", 3.1415926535);      # prints 3.142
  102.  
  103.       The POSIX module (part of the    standard perl distribution)
  104.       implements _c_e_i_l(), _f_l_o_o_r(), and a number of other
  105.       mathematical and trigonometric functions.
  106.  
  107.           use POSIX;
  108.           $ceil   =    ceil(3.5);              # 4
  109.           $floor  =    floor(3.5);              # 3
  110.  
  111.       In 5.000 to 5.003 Perls, trigonometry    was done in the
  112.       Math::Complex    module.     With 5.004, the Math::Trig module
  113.       (part    of the standard    perl distribution) implements the
  114.       trigonometric    functions. Internally it uses the
  115.       Math::Complex    module and some    functions can break out    from
  116.       the real axis    into the complex plane,    for example the
  117.       inverse sine of 2.
  118.  
  119.       Rounding in financial    applications can have serious
  120.       implications,    and the    rounding method    used should be
  121.       specified precisely.    In these cases,    it probably pays not
  122.       to trust whichever system rounding is    being used by Perl,
  123.       but to instead implement the rounding    function you need
  124.       yourself.
  125.  
  126.  
  127.  
  128.  
  129.      Page 2                        (printed 10/23/98)
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  137.  
  138.  
  139.  
  140.       HHHHoooowwww ddddoooo IIII ccccoooonnnnvvvveeeerrrrtttt bbbbiiiittttssss    iiiinnnnttttoooo iiiinnnnttttssss????
  141.  
  142.       To turn a string of 1s and 0s    like 10110110 into a scalar
  143.       containing its binary    value, use the _p_a_c_k() function
  144.       (documented in the section on    _p_a_c_k in    the _p_e_r_l_f_u_n_c manpage):
  145.  
  146.           $decimal = pack('B8', '10110110');
  147.  
  148.       Here's an example of going the other way:
  149.  
  150.           $binary_string = join('',    unpack('B*', "\x29"));
  151.  
  152.  
  153.       HHHHoooowwww ddddoooo IIII mmmmuuuullllttttiiiippppllllyyyy mmmmaaaattttrrrriiiicccceeeessss????
  154.  
  155.       Use the Math::Matrix or Math::MatrixReal modules (available
  156.       from CPAN) or    the PDL    extension (also    available from CPAN).
  157.  
  158.       HHHHoooowwww ddddoooo IIII ppppeeeerrrrffffoooorrrrmmmm aaaannnn ooooppppeeeerrrraaaattttiiiioooonnnn    oooonnnn aaaa sssseeeerrrriiiieeeessss ooooffff iiiinnnntttteeeeggggeeeerrrrssss????
  159.  
  160.       To call a function on    each element in    an array, and collect
  161.       the results, use:
  162.  
  163.           @results = map { my_func($_) } @array;
  164.  
  165.       For example:
  166.  
  167.           @triple =    map { 3    * $_ } @single;
  168.  
  169.       To call a function on    each element of    an array, but ignore
  170.       the results:
  171.  
  172.           foreach $iterator    (@array) {
  173.           &my_func($iterator);
  174.           }
  175.  
  176.       To call a function on    each integer in    a (small) range, you
  177.       ccccaaaannnn use:
  178.  
  179.           @results = map { &my_func($_) } (5 .. 25);
  180.  
  181.       but you should be aware that the .. operator creates an
  182.       array    of all integers    in the range.  This can    take a lot of
  183.       memory for large ranges.  Instead use:
  184.  
  185.           @results = ();
  186.           for ($i=5; $i < 500_005; $i++) {
  187.           push(@results, &my_func($i));
  188.           }
  189.  
  190.  
  191.  
  192.  
  193.  
  194.  
  195.      Page 3                        (printed 10/23/98)
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  203.  
  204.  
  205.  
  206.       HHHHoooowwww ccccaaaannnn IIII oooouuuuttttppppuuuutttt RRRRoooommmmaaaannnn nnnnuuuummmmeeeerrrraaaallllssss????
  207.  
  208.       Get the http://www.perl.com/CPAN/modules/by-module/Roman
  209.       module.
  210.  
  211.       WWWWhhhhyyyy aaaarrrreeeennnn''''tttt mmmmyyyy    rrrraaaannnnddddoooommmm nnnnuuuummmmbbbbeeeerrrrssss rrrraaaannnnddddoooommmm????
  212.  
  213.       The short explanation    is that    you're getting pseudorandom
  214.       numbers, not random ones, because computers are good at
  215.       being    predictable and    bad at being random (despite
  216.       appearances caused by    bugs in    your programs :-).  A longer
  217.       explanation is available on
  218.       http://www.perl.com/CPAN/doc/FMTEYEWTK/random, courtesy of
  219.       Tom Phoenix.    John von Neumann said, ``Anyone    who attempts
  220.       to generate random numbers by    deterministic means is,    of
  221.       course, living in a state of sin.''
  222.  
  223.       You should also check    out the    Math::TrulyRandom module from
  224.       CPAN.     It uses the imperfections in your system's timer to
  225.       generate random numbers, but this takes quite    a while.  If
  226.       you want a better pseudorandom generator than    comes with
  227.       your operating system, look at ``Numerical Recipes in    C'' at
  228.       http://nr.harvard.edu/nr/bookc.html .
  229.  
  230.      DDDDaaaattttaaaa:::: DDDDaaaatttteeeessss
  231.       HHHHoooowwww ddddoooo IIII ffffiiiinnnndddd    tttthhhheeee wwwweeeeeeeekkkk----ooooffff----tttthhhheeee----yyyyeeeeaaaarrrr////ddddaaaayyyy----ooooffff----tttthhhheeee----yyyyeeeeaaaarrrr????
  232.  
  233.       The day of the year is in the    array returned by _l_o_c_a_l_t_i_m_e()
  234.       (see the section on _l_o_c_a_l_t_i_m_e    in the _p_e_r_l_f_u_n_c    manpage):
  235.  
  236.           $day_of_year = (localtime(time()))[7];
  237.  
  238.       or more legibly (in 5.004 or higher):
  239.  
  240.           use Time::localtime;
  241.           $day_of_year = localtime(time())->yday;
  242.  
  243.       You can find the week    of the year by dividing    this by    7:
  244.  
  245.           $week_of_year = int($day_of_year / 7);
  246.  
  247.       Of course, this believes that    weeks start at zero.  The
  248.       Date::Calc module from CPAN has a lot    of date    calculation
  249.       functions, including day of the year,    week of    the year, and
  250.       so on.   Note    that not all business consider ``week 1'' to
  251.       be the same; for example, American business often consider
  252.       the first week with a    Monday in it to    be Work    Week #1,
  253.       despite ISO 8601, which consider WW1 to be the frist week
  254.       with a Thursday in it.
  255.  
  256.  
  257.  
  258.  
  259.  
  260.  
  261.      Page 4                        (printed 10/23/98)
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  269.  
  270.  
  271.  
  272.       HHHHoooowwww ccccaaaannnn IIII ccccoooommmmppppaaaarrrreeee ttttwwwwoooo    ddddaaaatttteeeessss aaaannnndddd ffffiiiinnnndddd tttthhhheeee ddddiiiiffffffffeeeerrrreeeennnncccceeee????
  273.  
  274.       If you're storing your dates as epoch    seconds    then simply
  275.       subtract one from the    other.    If you've got a    structured
  276.       date (distinct year, day, month, hour, minute, seconds
  277.       values) then use one of the Date::Manip and Date::Calc
  278.       modules from CPAN.
  279.  
  280.       HHHHoooowwww ccccaaaannnn IIII ttttaaaakkkkeeee aaaa ssssttttrrrriiiinnnngggg aaaannnndddd ttttuuuurrrrnnnn iiiitttt iiiinnnnttttoooo eeeeppppoooocccchhhh sssseeeeccccoooonnnnddddssss????
  281.  
  282.       If it's a regular enough string that it always has the same
  283.       format, you can split    it up and pass the parts to timelocal
  284.       in the standard Time::Local module.  Otherwise, you should
  285.       look into the    Date::Calc and Date::Manip modules from    CPAN.
  286.  
  287.       HHHHoooowwww ccccaaaannnn IIII ffffiiiinnnndddd tttthhhheeee JJJJuuuulllliiiiaaaannnn DDDDaaaayyyy????
  288.  
  289.       Neither Date::Manip nor Date::Calc deal with Julian days.
  290.       Instead, there is an example of Julian date calculation that
  291.       should help you in
  292.       http://www.perl.com/CPAN/authors/David_Muir_Sharnoff/modules/Time/JulianDay.pm.gz
  293.       .
  294.  
  295.       DDDDooooeeeessss PPPPeeeerrrrllll hhhhaaaavvvveeee aaaa yyyyeeeeaaaarrrr    2222000000000000 pppprrrroooobbbblllleeeemmmm????  IIIIssss PPPPeeeerrrrllll YYYY2222KKKK ccccoooommmmpppplllliiiiaaaannnntttt????
  296.  
  297.       Short    answer:    No, Perl does not have a Year 2000 problem.
  298.       Yes, Perl is Y2K compliant.  The programmers you're hired to
  299.       use it, however, probably are    not.
  300.  
  301.       Long answer: Perl is just as Y2K compliant as    your pencil--
  302.       no more, and no less.     The date and time functions supplied
  303.       with perl (gmtime and    localtime) supply adequate information
  304.       to determine the year    well beyond 2000 (2038 is when trouble
  305.       strikes for 32-bit machines).     The year returned by these
  306.       functions when used in an array context is the year minus
  307.       1900.     For years between 1910    and 1999 this _h_a_p_p_e_n_s to be a
  308.       2-digit decimal number. To avoid the year 2000 problem
  309.       simply do not    treat the year as a 2-digit number.  It    isn't.
  310.  
  311.       When _g_m_t_i_m_e()    and _l_o_c_a_l_t_i_m_e()    are used in scalar context
  312.       they return a    timestamp string that contains a fully-
  313.       expanded year.  For example, $timestamp = gmtime(1005613200)
  314.       sets $timestamp to "Tue Nov 13 01:00:00 2001".  There's no
  315.       year 2000 problem here.
  316.  
  317.       That doesn't mean that Perl can't be used to create non-Y2K
  318.       compliant programs.  It can.    But so can your    pencil.     It's
  319.       the fault of the user, not the language.  At the risk    of
  320.       inflaming the    NRA: ``Perl doesn't break Y2K, people do.''
  321.       See http://language.perl.com/news/y2k.html for a longer
  322.       exposition.
  323.  
  324.  
  325.  
  326.  
  327.      Page 5                        (printed 10/23/98)
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  335.  
  336.  
  337.  
  338.      DDDDaaaattttaaaa:::: SSSSttttrrrriiiinnnnggggssss
  339.       HHHHoooowwww ddddoooo IIII vvvvaaaalllliiiiddddaaaatttteeee iiiinnnnppppuuuutttt????
  340.  
  341.       The answer to    this question is usually a regular expression,
  342.       perhaps with auxiliary logic.     See the more specific
  343.       questions (numbers, mail addresses, etc.) for    details.
  344.  
  345.       HHHHoooowwww ddddoooo IIII uuuunnnneeeessssccccaaaappppeeee aaaa ssssttttrrrriiiinnnngggg????
  346.  
  347.       It depends just what you mean    by ``escape''.    URL escapes
  348.       are dealt with in the    _p_e_r_l_f_a_q_9 manpage.  Shell escapes with
  349.       the backslash    (\) character are removed with:
  350.  
  351.           s/\\(.)/$1/g;
  352.  
  353.       This won't expand "\n" or "\t" or any    other special escapes.
  354.  
  355.       HHHHoooowwww ddddoooo IIII rrrreeeemmmmoooovvvveeee ccccoooonnnnsssseeeeccccuuuuttttiiiivvvveeee ppppaaaaiiiirrrrssss ooooffff cccchhhhaaaarrrraaaacccctttteeeerrrrssss????
  356.  
  357.       To turn "abbcccd" into "abccd":
  358.  
  359.           s/(.)\1/$1/g;
  360.  
  361.  
  362.       HHHHoooowwww ddddoooo IIII eeeexxxxppppaaaannnndddd ffffuuuunnnnccccttttiiiioooonnnn ccccaaaallllllllssss iiiinnnn aaaa ssssttttrrrriiiinnnngggg????
  363.  
  364.       This is documented in    the _p_e_r_l_r_e_f manpage.  In general, this
  365.       is fraught with quoting and readability problems, but    it is
  366.       possible.  To    interpolate a subroutine call (in list
  367.       context) into    a string:
  368.  
  369.           print "My    sub returned @{[mysub(1,2,3)]} that time.\n";
  370.  
  371.       If you prefer    scalar context,    similar    chicanery is also
  372.       useful for arbitrary expressions:
  373.  
  374.           print "That yields ${\($n    + 5)} widgets\n";
  375.  
  376.       Version 5.004    of Perl    had a bug that gave list context to
  377.       the expression in ${...}, but    this is    fixed in version
  378.       5.005.
  379.  
  380.       See also ``How can I expand variables    in text    strings?'' in
  381.       this section of the FAQ.
  382.  
  383.       HHHHoooowwww ddddoooo IIII ffffiiiinnnndddd    mmmmaaaattttcccchhhhiiiinnnngggg////nnnneeeessssttttiiiinnnngggg aaaannnnyyyytttthhhhiiiinnnngggg????
  384.  
  385.       This isn't something that can    be done    in one regular
  386.       expression, no matter    how complicated.  To find something
  387.       between two single characters, a pattern like    /x([^x]*)x/
  388.       will get the intervening bits    in $1. For multiple ones, then
  389.       something more like /alpha(.*?)omega/    would be needed.  But
  390.  
  391.  
  392.  
  393.      Page 6                        (printed 10/23/98)
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  401.  
  402.  
  403.  
  404.       none of these    deals with nested patterns, nor    can they.  For
  405.       that you'll have to write a parser.
  406.  
  407.       If you are serious about writing a parser, there are a
  408.       number of modules or oddities    that will make your life a lot
  409.       easier.  There is the    CPAN module Parse::RecDescent, the
  410.       standard module Text::Balanced, the byacc program, and
  411.       Mark-Jason Dominus's excellent _p_y tool at
  412.       http://www.plover.com/~mjd/perl/py/ .
  413.  
  414.       One simple destructive, inside-out approach that you might
  415.       try is to pull out the smallest nesting parts    one at a time:
  416.  
  417.           while (s//BEGIN((?:(?!BEGIN)(?!END).)*)END/gs) {
  418.           # do something with $1
  419.           }
  420.  
  421.  
  422.       HHHHoooowwww ddddoooo IIII rrrreeeevvvveeeerrrrsssseeee aaaa ssssttttrrrriiiinnnngggg????
  423.  
  424.       Use _r_e_v_e_r_s_e()    in scalar context, as documented in the
  425.       reverse entry    in the _p_e_r_l_f_u_n_c    manpage.
  426.  
  427.           $reversed    = reverse $string;
  428.  
  429.  
  430.       HHHHoooowwww ddddoooo IIII eeeexxxxppppaaaannnndddd ttttaaaabbbbssss iiiinnnn aaaa ssssttttrrrriiiinnnngggg????
  431.  
  432.       You can do it    yourself:
  433.  
  434.           1    while $string =~ s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;
  435.  
  436.       Or you can just use the Text::Tabs module (part of the
  437.       standard perl    distribution).
  438.  
  439.           use Text::Tabs;
  440.           @expanded_lines =    expand(@lines_with_tabs);
  441.  
  442.  
  443.       HHHHoooowwww ddddoooo IIII rrrreeeeffffoooorrrrmmmmaaaatttt aaaa ppppaaaarrrraaaaggggrrrraaaapppphhhh????
  444.  
  445.       Use Text::Wrap (part of the standard perl distribution):
  446.  
  447.           use Text::Wrap;
  448.           print wrap("\t", '  ', @paragraphs);
  449.  
  450.       The paragraphs you give to Text::Wrap    should not contain
  451.       embedded newlines.  Text::Wrap doesn't justify the lines
  452.       (flush-right).
  453.  
  454.  
  455.  
  456.  
  457.  
  458.  
  459.      Page 7                        (printed 10/23/98)
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  467.  
  468.  
  469.  
  470.       HHHHoooowwww ccccaaaannnn IIII aaaacccccccceeeessssssss////cccchhhhaaaannnnggggeeee tttthhhheeee ffffiiiirrrrsssstttt NNNN lllleeeetttttttteeeerrrrssss ooooffff aaaa ssssttttrrrriiiinnnngggg????
  471.  
  472.       There    are many ways.    If you just want to grab a copy, use
  473.       _s_u_b_s_t_r():
  474.  
  475.           $first_byte = substr($a, 0, 1);
  476.  
  477.       If you want to modify    part of    a string, the simplest way is
  478.       often    to use _s_u_b_s_t_r()    as an lvalue:
  479.  
  480.           substr($a, 0, 3) = "Tom";
  481.  
  482.       Although those with a    pattern    matching kind of thought
  483.       process will likely prefer:
  484.  
  485.           $a =~ s/^.../Tom/;
  486.  
  487.  
  488.       HHHHoooowwww ddddoooo IIII cccchhhhaaaannnnggggeeee tttthhhheeee NNNNtttthhhh ooooccccccccuuuurrrrrrrreeeennnncccceeee ooooffff    ssssoooommmmeeeetttthhhhiiiinnnngggg????
  489.  
  490.       You have to keep track of N yourself.     For example, let's
  491.       say you want to change the fifth occurrence of "whoever" or
  492.       "whomever" into "whosoever" or "whomsoever", case
  493.       insensitively.
  494.  
  495.           $count = 0;
  496.           s{((whom?)ever)}{
  497.           ++$count == 5          # is it the 5th?
  498.               ?    "${2}soever"      # yes, swap
  499.               :    $1          # renege and leave it    there
  500.           }igex;
  501.  
  502.       In the more general case, you    can use    the /g modifier    in a
  503.       while    loop, keeping count of matches.
  504.  
  505.           $WANT = 3;
  506.           $count = 0;
  507.           while (/(\w+)\s+fish\b/gi) {
  508.           if (++$count == $WANT) {
  509.               print "The third fish is a $1 one.\n";
  510.               #    Warning: don't `last' out of this loop
  511.           }
  512.           }
  513.  
  514.       That prints out: "The    third fish is a    red one."  You can
  515.       also use a repetition    count and repeated pattern like    this:
  516.  
  517.           /(?:\w+\s+fish\s+){2}(\w+)\s+fish/i;
  518.  
  519.  
  520.  
  521.  
  522.  
  523.  
  524.  
  525.      Page 8                        (printed 10/23/98)
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  533.  
  534.  
  535.  
  536.       HHHHoooowwww ccccaaaannnn IIII ccccoooouuuunnnntttt tttthhhheeee nnnnuuuummmmbbbbeeeerrrr ooooffff    ooooccccccccuuuurrrrrrrreeeennnncccceeeessss ooooffff aaaa ssssuuuubbbbssssttttrrrriiiinnnngggg
  537.       wwwwiiiitttthhhhiiiinnnn aaaa ssssttttrrrriiiinnnngggg????
  538.  
  539.       There    are a number of    ways, with varying efficiency: If you
  540.       want a count of a certain single character (X) within    a
  541.       string, you can use the tr///    function like so:
  542.  
  543.           $string =    "ThisXlineXhasXsomeXx'sXinXit":
  544.           $count = ($string    =~ tr/X//);
  545.           print "There are $count X    charcters in the string";
  546.  
  547.       This is fine if you are just looking for a single character.
  548.       However, if you are trying to    count multiple character
  549.       substrings within a larger string, tr/// won't work.    What
  550.       you can do is    wrap a _w_h_i_l_e() loop around a global pattern
  551.       match.  For example, let's count negative integers:
  552.  
  553.           $string =    "-9 55 48 -2 23    -76 4 14 -44";
  554.           while ($string =~    /-\d+/g) { $count++ }
  555.           print "There are $count negative numbers in the string";
  556.  
  557.  
  558.       HHHHoooowwww ddddoooo IIII ccccaaaappppiiiittttaaaalllliiiizzzzeeee aaaallllllll tttthhhheeee wwwwoooorrrrddddssss oooonnnn oooonnnneeee lllliiiinnnneeee????
  559.  
  560.       To make the first letter of each word    upper case:
  561.  
  562.           $line    =~ s/\b(\w)/\U$1/g;
  563.  
  564.       This has the strange effect of turning "don't    do it" into
  565.       "Don'T Do It".  Sometimes you    might want this, instead
  566.       (Suggested by    Brian Foy):
  567.  
  568.           $string =~ s/ (
  569.                (^\w)    #at    the beginning of the line
  570.                  |        # or
  571.                (\s\w)   #preceded by whitespace
  572.                  )
  573.               /\U$1/xg;
  574.           $string =~ /([\w']+)/\u\L$1/g;
  575.  
  576.       To make the whole line upper case:
  577.  
  578.           $line    = uc($line);
  579.  
  580.       To force each    word to    be lower case, with the    first letter
  581.       upper    case:
  582.  
  583.           $line    =~ s/(\w+)/\u\L$1/g;
  584.  
  585.       You can (and probably    should)    enable locale awareness    of
  586.       those    characters by placing a    use locale pragma in your
  587.       program.  See    the _p_e_r_l_l_o_c_a_l_e manpage for endless details on
  588.  
  589.  
  590.  
  591.      Page 9                        (printed 10/23/98)
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  599.  
  600.  
  601.  
  602.       locales.
  603.  
  604.       HHHHoooowwww ccccaaaannnn IIII sssspppplllliiiitttt aaaa [[[[cccchhhhaaaarrrraaaacccctttteeeerrrr]]]]    ddddeeeelllliiiimmmmiiiitttteeeedddd ssssttttrrrriiiinnnngggg eeeexxxxcccceeeepppptttt    wwwwhhhheeeennnn
  605.       iiiinnnnssssiiiiddddeeee [[[[cccchhhhaaaarrrraaaacccctttteeeerrrr]]]]???? ((((CCCCoooommmmmmmmaaaa----sssseeeeppppaaaarrrraaaatttteeeedddd ffffiiiilllleeeessss))))
  606.  
  607.       Take the example case    of trying to split a string that is
  608.       comma-separated into its different fields.  (We'll pretend
  609.       you said comma-separated, not    comma-delimited, which is
  610.       different and    almost never what you mean.) You can't use
  611.       split(/,/) because you shouldn't split if the    comma is
  612.       inside quotes.  For example, take a data line    like this:
  613.  
  614.           SAR001,"","Cimetrix, Inc","Bob Smith","CAM",N,8,1,0,7,"Error, Core Dumped"
  615.  
  616.       Due to the restriction of the    quotes,    this is    a fairly
  617.       complex problem.  Thankfully,    we have    Jeffrey    Friedl,    author
  618.       of a highly recommended book on regular expressions, to
  619.       handle these for us.    He suggests (assuming your string is
  620.       contained in $text):
  621.  
  622.            @new = ();
  623.            push(@new, $+) while $text =~ m{
  624.            "([^\"\\]*(?:\\.[^\"\\]*)*)",?  # groups the    phrase inside the quotes
  625.          | ([^,]+),?
  626.          | ,
  627.            }gx;
  628.            push(@new, undef) if substr($text,-1,1) eq ',';
  629.  
  630.       If you want to represent quotation marks inside a
  631.       quotation-mark-delimited field, escape them with backslashes
  632.       (eg, "like \"this\"".     Unescaping them is a task addressed
  633.       earlier in this section.
  634.  
  635.       Alternatively, the Text::ParseWords module (part of the
  636.       standard perl    distribution) lets you say:
  637.  
  638.           use Text::ParseWords;
  639.           @new = quotewords(",", 0,    $text);
  640.  
  641.  
  642.       HHHHoooowwww ddddoooo IIII ssssttttrrrriiiipppp bbbbllllaaaannnnkkkk ssssppppaaaacccceeee ffffrrrroooommmm tttthhhheeee bbbbeeeeggggiiiinnnnnnnniiiinnnngggg////eeeennnndddd ooooffff aaaa
  643.       ssssttttrrrriiiinnnngggg????
  644.  
  645.       Although the simplest    approach would seem to be:
  646.  
  647.           $string =~ s/^\s*(.*?)\s*$/$1/;
  648.  
  649.       This is unneccesarily    slow, destructive, and fails with
  650.       embedded newlines.  It is much better    faster to do this in
  651.       two steps:
  652.  
  653.  
  654.  
  655.  
  656.  
  657.      Page 10                        (printed 10/23/98)
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  665.  
  666.  
  667.  
  668.           $string =~ s/^\s+//;
  669.           $string =~ s/\s+$//;
  670.  
  671.       Or more nicely written as:
  672.  
  673.           for ($string) {
  674.           s/^\s+//;
  675.           s/\s+$//;
  676.           }
  677.  
  678.       This idiom takes advantage of    the foreach loop's aliasing
  679.       behavior to factor out common    code.  You can do this on
  680.       several strings at once, or arrays, or even the values of a
  681.       hash if you use a slide:
  682.  
  683.           #    trim whitespace    in the scalar, the array,
  684.           #    and all    the values in the hash
  685.           foreach ($scalar,    @array,    @hash{keys %hash}) {
  686.           s/^\s+//;
  687.           s/\s+$//;
  688.           }
  689.  
  690.  
  691.       HHHHoooowwww ddddoooo IIII eeeexxxxttttrrrraaaacccctttt sssseeeelllleeeecccctttteeeedddd ccccoooolllluuuummmmnnnnssss ffffrrrroooommmm aaaa ssssttttrrrriiiinnnngggg????
  692.  
  693.       Use _s_u_b_s_t_r() or _u_n_p_a_c_k(), both documented in the _p_e_r_l_f_u_n_c
  694.       manpage.  If you prefer thinking in terms of columns instead
  695.       of widths, you can use this kind of thing:
  696.  
  697.           #    determine the unpack format needed to split Linux ps output
  698.           #    arguments are cut columns
  699.           my $fmt =    cut2fmt(8, 14, 20, 26, 30, 34, 41, 47, 59, 63, 67, 72);
  700.  
  701.           sub cut2fmt {
  702.           my(@positions) = @_;
  703.           my $template    = '';
  704.           my $lastpos    = 1;
  705.           for my $place    (@positions) {
  706.               $template    .= "A" . ($place - $lastpos) . " ";
  707.               $lastpos     = $place;
  708.           }
  709.           $template .= "A*";
  710.           return $template;
  711.           }
  712.  
  713.  
  714.       HHHHoooowwww ddddoooo IIII ffffiiiinnnndddd    tttthhhheeee ssssoooouuuunnnnddddeeeexxxx vvvvaaaalllluuuueeee ooooffff aaaa ssssttttrrrriiiinnnngggg????
  715.  
  716.       Use the standard Text::Soundex module    distributed with perl.
  717.  
  718.  
  719.  
  720.  
  721.  
  722.  
  723.      Page 11                        (printed 10/23/98)
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  731.  
  732.  
  733.  
  734.       HHHHoooowwww ccccaaaannnn IIII eeeexxxxppppaaaannnndddd vvvvaaaarrrriiiiaaaabbbblllleeeessss iiiinnnn    tttteeeexxxxtttt ssssttttrrrriiiinnnnggggssss????
  735.  
  736.       Let's    assume that you    have a string like:
  737.  
  738.           $text = 'this has    a $foo in it and a $bar';
  739.  
  740.       If those were    both global variables, then this would
  741.       suffice:
  742.  
  743.           $text =~ s/\$(\w+)/${$1}/g;
  744.  
  745.       But since they are probably lexicals,    or at least, they
  746.       could    be, you'd have to do this:
  747.  
  748.           $text =~ s/(\$\w+)/$1/eeg;
  749.           die if $@;          # needed on /ee, not /e
  750.  
  751.       It's probably    better in the general case to treat those
  752.       variables as entries in some special hash.  For example:
  753.  
  754.           %user_defs = (
  755.           foo  => 23,
  756.           bar  => 19,
  757.           );
  758.           $text =~ s/\$(\w+)/$user_defs{$1}/g;
  759.  
  760.       See also ``How do I expand function calls in a string?'' in
  761.       this section of the FAQ.
  762.  
  763.       WWWWhhhhaaaatttt''''ssss wwwwrrrroooonnnngggg wwwwiiiitttthhhh aaaallllwwwwaaaayyyyssss qqqquuuuoooottttiiiinnnngggg """"$$$$vvvvaaaarrrrssss""""????
  764.  
  765.       The problem is that those double-quotes force
  766.       stringification, coercing numbers and    references into
  767.       strings, even    when you don't want them to be.
  768.  
  769.       If you get used to writing odd things    like these:
  770.  
  771.           print "$var";      # BAD
  772.           $new = "$old";      # BAD
  773.           somefunc("$var");      # BAD
  774.  
  775.       You'll be in trouble.     Those should (in 99.8%    of the cases)
  776.       be the simpler and more direct:
  777.  
  778.           print $var;
  779.           $new = $old;
  780.           somefunc($var);
  781.  
  782.       Otherwise, besides slowing you down, you're going to break
  783.       code when the    thing in the scalar is actually    neither    a
  784.       string nor a number, but a reference:
  785.  
  786.  
  787.  
  788.  
  789.      Page 12                        (printed 10/23/98)
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  797.  
  798.  
  799.  
  800.           func(\@array);
  801.           sub func {
  802.           my $aref = shift;
  803.           my $oref = "$aref";  # WRONG
  804.           }
  805.  
  806.       You can also get into    subtle problems    on those few
  807.       operations in    Perl that actually do care about the
  808.       difference between a string and a number, such as the
  809.       magical ++ autoincrement operator or the _s_y_s_c_a_l_l() function.
  810.  
  811.       Stringification also destroys    arrays.
  812.  
  813.           @lines = `command`;
  814.           print "@lines";          # WRONG - extra blanks
  815.           print @lines;          # right
  816.  
  817.  
  818.       WWWWhhhhyyyy ddddoooonnnn''''tttt mmmmyyyy <<<<<<<<HHHHEEEERRRREEEE ddddooooccccuuuummmmeeeennnnttttssss    wwwwoooorrrrkkkk????
  819.  
  820.       Check    for these three    things:
  821.  
  822.       1. There must    be no space after the << part.
  823.  
  824.       2. There (probably) should be    a semicolon at the end.
  825.  
  826.       3. You can't (easily)    have any space in front    of the tag.
  827.  
  828.       If you want to indent    the text in the    here document, you can
  829.       do this:
  830.  
  831.           #    all in one
  832.           ($VAR = <<HERE_TARGET) =~    s/^\s+//gm;
  833.           your text
  834.           goes here
  835.           HERE_TARGET
  836.  
  837.       But the HERE_TARGET must still be flush against the margin.
  838.       If you want that indented also, you'll have to quote in the
  839.       indentation.
  840.  
  841.           ($quote =    <<'    FINIS') =~ s/^\s+//gm;
  842.               ...we will have peace, when you and all your works have
  843.               perished--and the    works of your dark master to whom you
  844.               would deliver us.    You are    a liar,    Saruman, and a corrupter
  845.               of men's hearts.    --Theoden in /usr/src/perl/taint.c
  846.           FINIS
  847.           $quote =~    s/\s*--/\n--/;
  848.  
  849.       A nice general-purpose fixer-upper function for indented
  850.       here documents follows.  It expects to be called with    a here
  851.       document as its argument.  It    looks to see whether each line
  852.  
  853.  
  854.  
  855.      Page 13                        (printed 10/23/98)
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  863.  
  864.  
  865.  
  866.       begins with a    common substring, and if so, strips that off.
  867.       Otherwise, it    takes the amount of leading white space    found
  868.       on the first line and    removes    that much off each subsequent
  869.       line.
  870.  
  871.           sub fix {
  872.           local    $_ = shift;
  873.           my ($white, $leader);     # common white    space and common leading string
  874.           if (/^\s*(?:([^\w\s]+)(\s*).*\n)(?:\s*\1\2?.*\n)+$/) {
  875.               ($white, $leader)    = ($2, quotemeta($1));
  876.           } else {
  877.               ($white, $leader)    = (/^(\s+)/, '');
  878.           }
  879.           s/^\s*?$leader(?:$white)?//gm;
  880.           return $_;
  881.           }
  882.  
  883.       This works with leading special strings, dynamically
  884.       determined:
  885.  
  886.           $remember_the_main = fix<<'    MAIN_INTERPRETER_LOOP';
  887.           @@@ int
  888.           @@@ runops() {
  889.           @@@      SAVEI32(runlevel);
  890.           @@@      runlevel++;
  891.           @@@      while    ( op = (*op->op_ppaddr)() ) ;
  892.           @@@      TAINT_NOT;
  893.           @@@      return 0;
  894.           @@@ }
  895.           MAIN_INTERPRETER_LOOP
  896.  
  897.       Or with a fixed amount of leading white space, with
  898.       remaining indentation    correctly preserved:
  899.  
  900.           $poem = fix<<EVER_ON_AND_ON;
  901.          Now far ahead the Road    has gone,
  902.             And    I must follow, if I can,
  903.          Pursuing it with eager    feet,
  904.             Until it joins some    larger way
  905.          Where many paths and errands meet.
  906.             And    whither    then? I    cannot say.
  907.               --Bilbo in /usr/src/perl/pp_ctl.c
  908.           EVER_ON_AND_ON
  909.  
  910.  
  911.      DDDDaaaattttaaaa:::: AAAArrrrrrrraaaayyyyssss
  912.       WWWWhhhhaaaatttt iiiissss tttthhhheeee ddddiiiiffffffffeeeerrrreeeennnncccceeee bbbbeeeettttwwwweeeeeeeennnn $$$$aaaarrrrrrrraaaayyyy[1] and @array[1]?
  913.  
  914.       The former is    a scalar value,    the latter an array slice,
  915.       which    makes it a list    with one (scalar) value.  You should
  916.       use $    when you want a    scalar value (most of the time)    and @
  917.       when you want    a list with one    scalar value in    it (very, very
  918.  
  919.  
  920.  
  921.      Page 14                        (printed 10/23/98)
  922.  
  923.  
  924.  
  925.  
  926.  
  927.  
  928.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  929.  
  930.  
  931.  
  932.       rarely; nearly never,    in fact).
  933.  
  934.       Sometimes it doesn't make a difference, but sometimes    it
  935.       does.     For example, compare:
  936.  
  937.           $good[0] = `some program that outputs several lines`;
  938.  
  939.       with
  940.  
  941.           @bad[0]  = `same program that outputs several lines`;
  942.  
  943.       The ----wwww flag will warn    you about these    matters.
  944.  
  945.       HHHHoooowwww ccccaaaannnn IIII eeeexxxxttttrrrraaaacccctttt jjjjuuuusssstttt tttthhhheeee uuuunnnniiiiqqqquuuueeee eeeelllleeeemmmmeeeennnnttttssss ooooffff    aaaannnn aaaarrrrrrrraaaayyyy????
  946.  
  947.       There    are several possible ways, depending on    whether    the
  948.       array    is ordered and whether you wish    to preserve the
  949.       ordering.
  950.  
  951.      assumes all true values in    the array)
  952.       a) If    @in is sorted, and you want @out to be sorted: (this
  953.  
  954.           $prev    = 'nonesuch';
  955.           @out = grep($_ ne $prev && ($prev = $_), @in);
  956.  
  957.           This is nice in that it doesn't use much extra memory,
  958.           simulating _u_n_i_q(1)'s behavior of removing    only adjacent
  959.           duplicates.  It's    less nice in that it won't work    with
  960.           false values like    undef, 0, or ""; "0 but    true" is ok,
  961.           though.
  962.  
  963.       b) If    you don't know whether @in is sorted:
  964.  
  965.           undef    %saw;
  966.           @out = grep(!$saw{$_}++, @in);
  967.  
  968.  
  969.       c) Like (b), but @in contains    only small integers:
  970.  
  971.           @out = grep(!$saw[$_]++, @in);
  972.  
  973.  
  974.       d) A way to do (b) without any loops or greps:
  975.  
  976.           undef    %saw;
  977.           @saw{@in} = ();
  978.           @out = sort keys %saw;  # remove sort    if undesired
  979.  
  980.  
  981.       e) Like (d), but @in contains    only small positive integers:
  982.  
  983.  
  984.  
  985.  
  986.  
  987.      Page 15                        (printed 10/23/98)
  988.  
  989.  
  990.  
  991.  
  992.  
  993.  
  994.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  995.  
  996.  
  997.  
  998.           undef    @ary;
  999.           @ary[@in] = @in;
  1000.           @out = @ary;
  1001.  
  1002.  
  1003.       HHHHoooowwww ccccaaaannnn IIII tttteeeellllllll wwwwhhhheeeetttthhhheeeerrrr aaaa lllliiiisssstttt    oooorrrr aaaarrrrrrrraaaayyyy ccccoooonnnnttttaaaaiiiinnnnssss aaaa cccceeeerrrrttttaaaaiiiinnnn
  1004.       eeeelllleeeemmmmeeeennnntttt????
  1005.  
  1006.       Hearing the word "in"    is an _i_ndication that you probably
  1007.       should have used a hash, not a list or array,    to store your
  1008.       data.     Hashes    are designed to    answer this question quickly
  1009.       and efficiently.  Arrays aren't.
  1010.  
  1011.       That being said, there are several ways to approach this.
  1012.       If you are going to make this    query many times over
  1013.       arbitrary string values, the fastest way is probably to
  1014.       invert the original array and    keep an    associative array
  1015.       lying    about whose keys are the first array's values.
  1016.  
  1017.           @blues = qw/azure    cerulean teal turquoise    lapis-lazuli/;
  1018.           undef %is_blue;
  1019.           for (@blues) { $is_blue{$_} = 1 }
  1020.  
  1021.       Now you can check whether $is_blue{$some_color}.  It might
  1022.       have been a good idea    to keep    the blues all in a hash    in the
  1023.       first    place.
  1024.  
  1025.       If the values    are all    small integers,    you could use a    simple
  1026.       indexed array.  This kind of an array    will take up less
  1027.       space:
  1028.  
  1029.           @primes =    (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31);
  1030.           undef @is_tiny_prime;
  1031.           for (@primes) { $is_tiny_prime[$_] = 1; }
  1032.  
  1033.       Now you check    whether    $is_tiny_prime[$some_number].
  1034.  
  1035.       If the values    in question are    integers instead of strings,
  1036.       you can save quite a lot of space by using bit strings
  1037.       instead:
  1038.  
  1039.           @articles    = ( 1..10, 150..2000, 2017 );
  1040.           undef $read;
  1041.           for (@articles) {    vec($read,$_,1)    = 1 }
  1042.  
  1043.       Now check whether vec($read,$n,1) is true for    some $n.
  1044.  
  1045.       Please do not    use
  1046.  
  1047.           $is_there    = grep $_ eq $whatever,    @array;
  1048.  
  1049.       or worse yet
  1050.  
  1051.  
  1052.  
  1053.      Page 16                        (printed 10/23/98)
  1054.  
  1055.  
  1056.  
  1057.  
  1058.  
  1059.  
  1060.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  1061.  
  1062.  
  1063.  
  1064.           $is_there    = grep /$whatever/, @array;
  1065.  
  1066.       These    are slow (checks every element even if the first
  1067.       matches), inefficient    (same reason), and potentially buggy
  1068.       (what    if there are regexp characters in $whatever?).
  1069.  
  1070.       HHHHoooowwww ddddoooo IIII ccccoooommmmppppuuuutttteeee tttthhhheeee ddddiiiiffffffffeeeerrrreeeennnncccceeee ooooffff ttttwwwwoooo aaaarrrrrrrraaaayyyyssss????  HHHHoooowwww ddddoooo IIII
  1071.       ccccoooommmmppppuuuutttteeee tttthhhheeee iiiinnnntttteeeerrrrsssseeeeccccttttiiiioooonnnn ooooffff ttttwwwwoooo aaaarrrrrrrraaaayyyyssss????
  1072.  
  1073.       Use a    hash.  Here's code to do both and more.     It assumes
  1074.       that each element is unique in a given array:
  1075.  
  1076.           @union = @intersection = @difference = ();
  1077.           %count = ();
  1078.           foreach $element (@array1, @array2) { $count{$element}++ }
  1079.           foreach $element (keys %count) {
  1080.           push @union, $element;
  1081.           push @{ $count{$element} > 1 ? \@intersection    : \@difference }, $element;
  1082.           }
  1083.  
  1084.  
  1085.       HHHHoooowwww ddddoooo IIII ffffiiiinnnndddd    tttthhhheeee ffffiiiirrrrsssstttt aaaarrrrrrrraaaayyyy    eeeelllleeeemmmmeeeennnntttt    ffffoooorrrr wwwwhhhhiiiicccchhhh aaaa ccccoooonnnnddddiiiittttiiiioooonnnn
  1086.       iiiissss ttttrrrruuuueeee????
  1087.  
  1088.       You can use this if you care about the index:
  1089.  
  1090.           for ($i=0; $i < @array; $i++) {
  1091.           if ($array[$i] eq "Waldo") {
  1092.               $found_index = $i;
  1093.               last;
  1094.           }
  1095.           }
  1096.  
  1097.       Now $found_index has what you    want.
  1098.  
  1099.       HHHHoooowwww ddddoooo IIII hhhhaaaannnnddddlllleeee lllliiiinnnnkkkkeeeedddd lllliiiissssttttssss????
  1100.  
  1101.       In general, you usually don't    need a linked list in Perl,
  1102.       since    with regular arrays, you can push and pop or shift and
  1103.       unshift at either end, or you    can use    splice to add and/or
  1104.       remove arbitrary number of elements at arbitrary points.
  1105.       Both pop and shift are both _O(1) operations on perl's
  1106.       dynamic arrays.  In the absence of shifts and    pops, push in
  1107.       general needs    to reallocate on the order every _l_o_g(N)    times,
  1108.       and unshift will need    to copy    pointers each time.
  1109.  
  1110.       If you really, really    wanted,    you could use structures as
  1111.       described in the _p_e_r_l_d_s_c manpage or the _p_e_r_l_t_o_o_t manpage and
  1112.       do just what the algorithm book tells    you to do.
  1113.  
  1114.  
  1115.  
  1116.  
  1117.  
  1118.  
  1119.      Page 17                        (printed 10/23/98)
  1120.  
  1121.  
  1122.  
  1123.  
  1124.  
  1125.  
  1126.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  1127.  
  1128.  
  1129.  
  1130.       HHHHoooowwww ddddoooo IIII hhhhaaaannnnddddlllleeee cccciiiirrrrccccuuuullllaaaarrrr lllliiiissssttttssss????
  1131.  
  1132.       Circular lists could be handled in the traditional fashion
  1133.       with linked lists, or    you could just do something like this
  1134.       with an array:
  1135.  
  1136.           unshift(@array, pop(@array));  # the last    shall be first
  1137.           push(@array, shift(@array));   # and vice    versa
  1138.  
  1139.  
  1140.       HHHHoooowwww ddddoooo IIII sssshhhhuuuufffffffflllleeee aaaannnn aaaarrrrrrrraaaayyyy rrrraaaannnnddddoooommmmllllyyyy????
  1141.  
  1142.       Use this:
  1143.  
  1144.           #    fisher_yates_shuffle( \@array )    :
  1145.           #    generate a random permutation of @array    in place
  1146.           sub fisher_yates_shuffle {
  1147.           my $array = shift;
  1148.           my $i;
  1149.           for ($i = @$array; --$i; ) {
  1150.               my $j = int rand ($i+1);
  1151.               next if $i == $j;
  1152.               @$array[$i,$j] = @$array[$j,$i];
  1153.           }
  1154.           }
  1155.  
  1156.           fisher_yates_shuffle( \@array );      # permutes @array in place
  1157.  
  1158.       You've probably seen shuffling algorithms that works using
  1159.       splice, randomly picking another element to swap the current
  1160.       element with:
  1161.  
  1162.           srand;
  1163.           @new = ();
  1164.           @old = 1 .. 10;  # just a    demo
  1165.           while (@old) {
  1166.           push(@new, splice(@old, rand @old, 1));
  1167.           }
  1168.  
  1169.       This is bad because splice is    already    _O(N), and since    you do
  1170.       it N times, you just invented    a quadratic algorithm; that
  1171.       is, _O(N**2).    This does not scale, although Perl is so
  1172.       efficient that you probably won't notice this    until you have
  1173.       rather largish arrays.
  1174.  
  1175.       HHHHoooowwww ddddoooo IIII pppprrrroooocccceeeessssssss////mmmmooooddddiiiiffffyyyy eeeeaaaacccchhhh eeeelllleeeemmmmeeeennnntttt ooooffff aaaannnn aaaarrrrrrrraaaayyyy????
  1176.  
  1177.       Use for/foreach:
  1178.  
  1179.  
  1180.  
  1181.  
  1182.  
  1183.  
  1184.  
  1185.      Page 18                        (printed 10/23/98)
  1186.  
  1187.  
  1188.  
  1189.  
  1190.  
  1191.  
  1192.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  1193.  
  1194.  
  1195.  
  1196.           for (@lines) {
  1197.           s/foo/bar/;      # change that    word
  1198.           y/XZ/ZX/;      # swap those letters
  1199.           }
  1200.  
  1201.       Here's another; let's    compute    spherical volumes:
  1202.  
  1203.           for (@volumes = @radii) {      # @volumes has changed parts
  1204.           $_ **= 3;
  1205.           $_ *=    (4/3) *    3.14159;  # this will be constant folded
  1206.           }
  1207.  
  1208.       If you want to do the    same thing to modify the values    of the
  1209.       hash,    you may    not use    the values function, oddly enough.
  1210.       You need a slice:
  1211.  
  1212.           for $orbit ( @orbits{keys    %orbits} ) {
  1213.           ($orbit **= 3) *= (4/3) * 3.14159;
  1214.           }
  1215.  
  1216.  
  1217.       HHHHoooowwww ddddoooo IIII sssseeeelllleeeecccctttt aaaa rrrraaaannnnddddoooommmm eeeelllleeeemmmmeeeennnntttt ffffrrrroooommmm    aaaannnn aaaarrrrrrrraaaayyyy????
  1218.  
  1219.       Use the _r_a_n_d() function (see the rand    entry in the _p_e_r_l_f_u_n_c
  1220.       manpage):
  1221.  
  1222.           #    at the top of the program:
  1223.           srand;              # not    needed for 5.004 and later
  1224.  
  1225.           #    then later on
  1226.           $index   = rand @array;
  1227.           $element = $array[$index];
  1228.  
  1229.       Make sure you    _o_n_l_y _c_a_l_l _s_r_a_n_d    _o_n_c_e _p_e_r _p_r_o_g_r_a_m, _i_f _t_h_e_n.  If
  1230.       you are calling it more than once (such as before each call
  1231.       to rand), you're almost certainly doing something wrong.
  1232.  
  1233.       HHHHoooowwww ddddoooo IIII ppppeeeerrrrmmmmuuuutttteeee NNNN eeeelllleeeemmmmeeeennnnttttssss ooooffff aaaa lllliiiisssstttt????
  1234.  
  1235.       Here's a little program that generates all permutations of
  1236.       all the words    on each    line of    input.    The algorithm embodied
  1237.       in the _p_e_r_m_u_t_e() function should work    on any list:
  1238.  
  1239.  
  1240.  
  1241.  
  1242.  
  1243.  
  1244.  
  1245.  
  1246.  
  1247.  
  1248.  
  1249.  
  1250.  
  1251.      Page 19                        (printed 10/23/98)
  1252.  
  1253.  
  1254.  
  1255.  
  1256.  
  1257.  
  1258.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  1259.  
  1260.  
  1261.  
  1262.           #!/usr/bin/perl -n
  1263.           #    tsc-permute: permute each word of input
  1264.           permute([split], []);
  1265.           sub permute {
  1266.           my @items = @{ $_[0] };
  1267.           my @perms = @{ $_[1] };
  1268.           unless (@items) {
  1269.               print "@perms\n";
  1270.           } else {
  1271.               my(@newitems,@newperms,$i);
  1272.               foreach $i (0 .. $#items)    {
  1273.               @newitems = @items;
  1274.               @newperms = @perms;
  1275.               unshift(@newperms, splice(@newitems, $i, 1));
  1276.               permute([@newitems], [@newperms]);
  1277.               }
  1278.           }
  1279.           }
  1280.  
  1281.  
  1282.       HHHHoooowwww ddddoooo IIII ssssoooorrrrtttt    aaaannnn aaaarrrrrrrraaaayyyy bbbbyyyy ((((aaaannnnyyyytttthhhhiiiinnnngggg))))????
  1283.  
  1284.       Supply a comparison function to _s_o_r_t() (described in the
  1285.       sort entry in    the _p_e_r_l_f_u_n_c manpage):
  1286.  
  1287.           @list = sort { $a    <=> $b } @list;
  1288.  
  1289.       The default sort function is cmp, string comparison, which
  1290.       would    sort (1, 2, 10)    into (1, 10, 2).  <=>, used above, is
  1291.       the numerical    comparison operator.
  1292.  
  1293.       If you have a    complicated function needed to pull out    the
  1294.       part you want    to sort    on, then don't do it inside the    sort
  1295.       function.  Pull it out first,    because    the sort BLOCK can be
  1296.       called many times for    the same element.  Here's an example
  1297.       of how to pull out the first word after the first number on
  1298.       each item, and then sort those words case-insensitively.
  1299.  
  1300.           @idx = ();
  1301.           for (@data) {
  1302.           ($item) = /\d+\s*(\S+)/;
  1303.           push @idx, uc($item);
  1304.           }
  1305.           @sorted =    @data[ sort { $idx[$a] cmp $idx[$b] } 0    .. $#idx ];
  1306.  
  1307.       Which    could also be written this way,    using a    trick that's
  1308.       come to be known as the Schwartzian Transform:
  1309.  
  1310.           @sorted =    map  { $_->[0] }
  1311.             sort { $a->[1] cmp $b->[1] }
  1312.             map  { [ $_, uc((/\d+\s*(\S+)/ )[0] ] }    @data;
  1313.  
  1314.  
  1315.  
  1316.  
  1317.      Page 20                        (printed 10/23/98)
  1318.  
  1319.  
  1320.  
  1321.  
  1322.  
  1323.  
  1324.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  1325.  
  1326.  
  1327.  
  1328.       If you need to sort on several fields, the following
  1329.       paradigm is useful.
  1330.  
  1331.           @sorted =    sort { field1($a) <=> field1($b) ||
  1332.                    field2($a) cmp field2($b) ||
  1333.                    field3($a) cmp field3($b)
  1334.                  }       @data;
  1335.  
  1336.       This can be conveniently combined with precalculation    of
  1337.       keys as given    above.
  1338.  
  1339.       See http://www.perl.com/CPAN/doc/FMTEYEWTK/sort.html for
  1340.       more about this approach.
  1341.  
  1342.       See also the question    below on sorting hashes.
  1343.  
  1344.       HHHHoooowwww ddddoooo IIII mmmmaaaannnniiiippppuuuullllaaaatttteeee aaaarrrrrrrraaaayyyyssss ooooffff    bbbbiiiittttssss????
  1345.  
  1346.       Use _p_a_c_k() and _u_n_p_a_c_k(), or else _v_e_c() and the bitwise
  1347.       operations.
  1348.  
  1349.       For example, this sets $vec to have bit N set    if $ints[N]
  1350.       was set:
  1351.  
  1352.           $vec = '';
  1353.           foreach(@ints) { vec($vec,$_,1) =    1 }
  1354.  
  1355.       And here's how, given    a vector in $vec, you can get those
  1356.       bits into your @ints array:
  1357.  
  1358.  
  1359.  
  1360.  
  1361.  
  1362.  
  1363.  
  1364.  
  1365.  
  1366.  
  1367.  
  1368.  
  1369.  
  1370.  
  1371.  
  1372.  
  1373.  
  1374.  
  1375.  
  1376.  
  1377.  
  1378.  
  1379.  
  1380.  
  1381.  
  1382.  
  1383.      Page 21                        (printed 10/23/98)
  1384.  
  1385.  
  1386.  
  1387.  
  1388.  
  1389.  
  1390.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  1391.  
  1392.  
  1393.  
  1394.           sub bitvec_to_list {
  1395.           my $vec = shift;
  1396.           my @ints;
  1397.           # Find null-byte density then    select best algorithm
  1398.           if ($vec =~ tr/\0// /    length $vec > 0.95) {
  1399.               use integer;
  1400.               my $i;
  1401.               #    This method is faster with mostly null-bytes
  1402.               while($vec =~ /[^\0]/g ) {
  1403.               $i = -9 + 8 *    pos $vec;
  1404.               push @ints, $i if vec($vec, ++$i, 1);
  1405.               push @ints, $i if vec($vec, ++$i, 1);
  1406.               push @ints, $i if vec($vec, ++$i, 1);
  1407.               push @ints, $i if vec($vec, ++$i, 1);
  1408.               push @ints, $i if vec($vec, ++$i, 1);
  1409.               push @ints, $i if vec($vec, ++$i, 1);
  1410.               push @ints, $i if vec($vec, ++$i, 1);
  1411.               push @ints, $i if vec($vec, ++$i, 1);
  1412.               }
  1413.           } else {
  1414.               #    This method is a fast general algorithm
  1415.               use integer;
  1416.               my $bits = unpack    "b*", $vec;
  1417.               push @ints, 0 if $bits =~    s/^(\d)// && $1;
  1418.               push @ints, pos $bits while($bits    =~ /1/g);
  1419.           }
  1420.           return \@ints;
  1421.           }
  1422.  
  1423.       This method gets faster the more sparse the bit vector is.
  1424.       (Courtesy of Tim Bunce and Winfried Koenig.)
  1425.  
  1426.       WWWWhhhhyyyy ddddooooeeeessss _d_e_f_i_n_e_d() return true on empty arrays and hashes?
  1427.  
  1428.       See the defined entry    in the _p_e_r_l_f_u_n_c    manpage    in the 5.004
  1429.       release or later of Perl.
  1430.  
  1431.      DDDDaaaattttaaaa:::: HHHHaaaasssshhhheeeessss ((((AAAAssssssssoooocccciiiiaaaattttiiiivvvveeee AAAArrrrrrrraaaayyyyssss))))
  1432.       HHHHoooowwww ddddoooo IIII pppprrrroooocccceeeessssssss aaaannnn eeeennnnttttiiiirrrreeee hhhhaaaasssshhhh????
  1433.  
  1434.       Use the _e_a_c_h() function (see the each    entry in the _p_e_r_l_f_u_n_c
  1435.       manpage) if you don't    care whether it's sorted:
  1436.  
  1437.           while ( ($key, $value) = each %hash) {
  1438.           print    "$key =    $value\n";
  1439.           }
  1440.  
  1441.       If you want it sorted, you'll    have to    use _f_o_r_e_a_c_h() on the
  1442.       result of sorting the    keys as    shown in an earlier question.
  1443.  
  1444.  
  1445.  
  1446.  
  1447.  
  1448.  
  1449.      Page 22                        (printed 10/23/98)
  1450.  
  1451.  
  1452.  
  1453.  
  1454.  
  1455.  
  1456.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  1457.  
  1458.  
  1459.  
  1460.       WWWWhhhhaaaatttt hhhhaaaappppppppeeeennnnssss iiiiffff IIII aaaadddddddd    oooorrrr rrrreeeemmmmoooovvvveeee kkkkeeeeyyyyssss ffffrrrroooommmm aaaa hhhhaaaasssshhhh wwwwhhhhiiiilllleeee
  1461.       iiiitttteeeerrrraaaattttiiiinnnngggg oooovvvveeeerrrr iiiitttt????
  1462.  
  1463.       Don't    do that.
  1464.  
  1465.       HHHHoooowwww ddddoooo IIII llllooooooookkkk    uuuupppp aaaa hhhhaaaasssshhhh eeeelllleeeemmmmeeeennnntttt bbbbyyyy vvvvaaaalllluuuueeee????
  1466.  
  1467.       Create a reverse hash:
  1468.  
  1469.           %by_value    = reverse %by_key;
  1470.           $key = $by_value{$value};
  1471.  
  1472.       That's not particularly efficient.  It would be more space-
  1473.       efficient to use:
  1474.  
  1475.           while (($key, $value) = each %by_key) {
  1476.           $by_value{$value} = $key;
  1477.           }
  1478.  
  1479.       If your hash could have repeated values, the methods above
  1480.       will only find one of    the associated keys.   This may    or may
  1481.       not worry you.
  1482.  
  1483.       HHHHoooowwww ccccaaaannnn IIII kkkknnnnoooowwww hhhhoooowwww mmmmaaaannnnyyyy eeeennnnttttrrrriiiieeeessss aaaarrrreeee iiiinnnn aaaa hhhhaaaasssshhhh????
  1484.  
  1485.       If you mean how many keys, then all you have to do is    take
  1486.       the scalar sense of the _k_e_y_s() function:
  1487.  
  1488.           $num_keys    = scalar keys %hash;
  1489.  
  1490.       In void context it just resets the iterator, which is    faster
  1491.       for tied hashes.
  1492.  
  1493.       HHHHoooowwww ddddoooo IIII ssssoooorrrrtttt    aaaa hhhhaaaasssshhhh ((((ooooppppttttiiiioooonnnnaaaallllllllyyyy bbbbyyyy vvvvaaaalllluuuueeee iiiinnnnsssstttteeeeaaaadddd ooooffff kkkkeeeeyyyy))))????
  1494.  
  1495.       Internally, hashes are stored    in a way that prevents you
  1496.       from imposing    an order on key-value pairs.  Instead, you
  1497.       have to sort a list of the keys or values:
  1498.  
  1499.           @keys = sort keys    %hash;      # sorted by key
  1500.           @keys = sort {
  1501.                   $hash{$a}    cmp $hash{$b}
  1502.               }    keys %hash;      # and    by value
  1503.  
  1504.       Here we'll do    a reverse numeric sort by value, and if    two
  1505.       keys are identical, sort by length of    key, and if that
  1506.       fails, by straight ASCII comparison of the keys (well,
  1507.       possibly modified by your locale -- see the _p_e_r_l_l_o_c_a_l_e
  1508.       manpage).
  1509.  
  1510.  
  1511.  
  1512.  
  1513.  
  1514.  
  1515.      Page 23                        (printed 10/23/98)
  1516.  
  1517.  
  1518.  
  1519.  
  1520.  
  1521.  
  1522.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  1523.  
  1524.  
  1525.  
  1526.           @keys = sort {
  1527.               $hash{$b} <=>    $hash{$a}
  1528.                     ||
  1529.               length($b) <=> length($a)
  1530.                     ||
  1531.                 $a cmp $b
  1532.           }    keys %hash;
  1533.  
  1534.  
  1535.       HHHHoooowwww ccccaaaannnn IIII aaaallllwwwwaaaayyyyssss kkkkeeeeeeeepppp    mmmmyyyy hhhhaaaasssshhhh    ssssoooorrrrtttteeeedddd????
  1536.  
  1537.       You can look into using the DB_File module and _t_i_e() using
  1538.       the $DB_BTREE    hash bindings as documented in the section on
  1539.       _I_n _M_e_m_o_r_y _D_a_t_a_b_a_s_e_s in the _D_B__F_i_l_e manpage.  The Tie::IxHash
  1540.       module from CPAN might also be instructive.
  1541.  
  1542.       WWWWhhhhaaaatttt''''ssss tttthhhheeee ddddiiiiffffffffeeeerrrreeeennnncccceeee    bbbbeeeettttwwwweeeeeeeennnn    """"ddddeeeelllleeeetttteeee"""" aaaannnndddd """"uuuunnnnddddeeeeffff"""" wwwwiiiitttthhhh
  1543.       hhhhaaaasssshhhheeeessss????
  1544.  
  1545.       Hashes are pairs of scalars: the first is the    key, the
  1546.       second is the    value.    The key    will be    coerced    to a string,
  1547.       although the value can be any    kind of    scalar:    string,
  1548.       number, or reference.     If a key $key is present in the
  1549.       array, exists($key) will return true.     The value for a given
  1550.       key can be undef, in which case $array{$key} will be undef
  1551.       while    $exists{$key} will return true.     This corresponds to
  1552.       ($key, undef)    being in the hash.
  1553.  
  1554.       Pictures help...  here's the %ary table:
  1555.  
  1556.             keys  values
  1557.           +------+------+
  1558.           |  a     |  3    |
  1559.           |  x     |  7    |
  1560.           |  d     |  0    |
  1561.           |  e     |  2    |
  1562.           +------+------+
  1563.  
  1564.       And these conditions hold
  1565.  
  1566.           $ary{'a'}              is true
  1567.           $ary{'d'}              is false
  1568.           defined $ary{'d'}          is true
  1569.           defined $ary{'a'}          is true
  1570.           exists $ary{'a'}          is true (perl5 only)
  1571.           grep ($_ eq 'a', keys    %ary)      is true
  1572.  
  1573.       If you now say
  1574.  
  1575.           undef    $ary{'a'}
  1576.  
  1577.       your table now reads:
  1578.  
  1579.  
  1580.  
  1581.      Page 24                        (printed 10/23/98)
  1582.  
  1583.  
  1584.  
  1585.  
  1586.  
  1587.  
  1588.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  1589.  
  1590.  
  1591.  
  1592.             keys  values
  1593.           +------+------+
  1594.           |  a     | undef|
  1595.           |  x     |  7    |
  1596.           |  d     |  0    |
  1597.           |  e     |  2    |
  1598.           +------+------+
  1599.  
  1600.       and these conditions now hold; changes in caps:
  1601.  
  1602.           $ary{'a'}              is FALSE
  1603.           $ary{'d'}              is false
  1604.           defined $ary{'d'}          is true
  1605.           defined $ary{'a'}          is FALSE
  1606.           exists $ary{'a'}          is true (perl5 only)
  1607.           grep ($_ eq 'a', keys    %ary)      is true
  1608.  
  1609.       Notice the last two: you have    an undef value,    but a defined
  1610.       key!
  1611.  
  1612.       Now, consider    this:
  1613.  
  1614.           delete $ary{'a'}
  1615.  
  1616.       your table now reads:
  1617.  
  1618.             keys  values
  1619.           +------+------+
  1620.           |  x     |  7    |
  1621.           |  d     |  0    |
  1622.           |  e     |  2    |
  1623.           +------+------+
  1624.  
  1625.       and these conditions now hold; changes in caps:
  1626.  
  1627.           $ary{'a'}              is false
  1628.           $ary{'d'}              is false
  1629.           defined $ary{'d'}          is true
  1630.           defined $ary{'a'}          is false
  1631.           exists $ary{'a'}          is FALSE (perl5 only)
  1632.           grep ($_ eq 'a', keys    %ary)      is FALSE
  1633.  
  1634.       See, the whole entry is gone!
  1635.  
  1636.       WWWWhhhhyyyy ddddoooonnnn''''tttt mmmmyyyy ttttiiiieeeedddd hhhhaaaasssshhhheeeessss mmmmaaaakkkkeeee    tttthhhheeee ddddeeeeffffiiiinnnneeeedddd////eeeexxxxiiiissssttttssss
  1637.       ddddiiiissssttttiiiinnnnccccttttiiiioooonnnn????
  1638.  
  1639.       They may or may not implement    the _E_X_I_S_T_S() and _D_E_F_I_N_E_D()
  1640.       methods differently.    For example, there isn't the concept
  1641.       of undef with    hashes that are    tied to    DBM* files. This means
  1642.       the true/false tables    above will give    different results when
  1643.       used on such a hash.    It also    means that exists and defined
  1644.  
  1645.  
  1646.  
  1647.      Page 25                        (printed 10/23/98)
  1648.  
  1649.  
  1650.  
  1651.  
  1652.  
  1653.  
  1654.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  1655.  
  1656.  
  1657.  
  1658.       do the same thing with a DBM*    file, and what they end    up
  1659.       doing    is not what they do with ordinary hashes.
  1660.  
  1661.       HHHHoooowwww ddddoooo IIII rrrreeeesssseeeetttt aaaannnn _e_a_c_h() operation part-way through?
  1662.  
  1663.       Using    keys %hash in scalar context returns the number    of
  1664.       keys in the hash _a_n_d resets the iterator associated with the
  1665.       hash.     You may need to do this if you    use last to exit a
  1666.       loop early so    that when you re-enter it, the hash iterator
  1667.       has been reset.
  1668.  
  1669.       HHHHoooowwww ccccaaaannnn IIII ggggeeeetttt    tttthhhheeee uuuunnnniiiiqqqquuuueeee kkkkeeeeyyyyssss    ffffrrrroooommmm ttttwwwwoooo hhhhaaaasssshhhheeeessss????
  1670.  
  1671.       First    you extract the    keys from the hashes into arrays, and
  1672.       then solve the uniquifying the array problem described
  1673.       above.  For example:
  1674.  
  1675.           %seen = ();
  1676.           for $element (keys(%foo),    keys(%bar)) {
  1677.           $seen{$element}++;
  1678.           }
  1679.           @uniq = keys %seen;
  1680.  
  1681.       Or more succinctly:
  1682.  
  1683.           @uniq = keys %{{%foo,%bar}};
  1684.  
  1685.       Or if    you really want    to save    space:
  1686.  
  1687.           %seen = ();
  1688.           while (defined ($key = each %foo)) {
  1689.           $seen{$key}++;
  1690.           }
  1691.           while (defined ($key = each %bar)) {
  1692.           $seen{$key}++;
  1693.           }
  1694.           @uniq = keys %seen;
  1695.  
  1696.  
  1697.       HHHHoooowwww ccccaaaannnn IIII ssssttttoooorrrreeee aaaa mmmmuuuullllttttiiiiddddiiiimmmmeeeennnnssssiiiioooonnnnaaaallll aaaarrrrrrrraaaayyyy iiiinnnn aaaa    DDDDBBBBMMMM ffffiiiilllleeee????
  1698.  
  1699.       Either stringify the structure yourself (no fun), or else
  1700.       get the MLDBM    (which uses Data::Dumper) module from CPAN and
  1701.       layer    it on top of either DB_File or GDBM_File.
  1702.  
  1703.       HHHHoooowwww ccccaaaannnn IIII mmmmaaaakkkkeeee mmmmyyyy hhhhaaaasssshhhh rrrreeeemmmmeeeemmmmbbbbeeeerrrr tttthhhheeee oooorrrrddddeeeerrrr IIII ppppuuuutttt eeeelllleeeemmmmeeeennnnttttssss
  1704.       iiiinnnnttttoooo iiiitttt????
  1705.  
  1706.       Use the Tie::IxHash from CPAN.
  1707.  
  1708.  
  1709.  
  1710.  
  1711.  
  1712.  
  1713.      Page 26                        (printed 10/23/98)
  1714.  
  1715.  
  1716.  
  1717.  
  1718.  
  1719.  
  1720.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  1721.  
  1722.  
  1723.  
  1724.           use Tie::IxHash;
  1725.           tie(%myhash, Tie::IxHash);
  1726.           for ($i=0; $i<20;    $i++) {
  1727.           $myhash{$i} =    2*$i;
  1728.           }
  1729.           @keys = keys %myhash;
  1730.           #    @keys =    (0,1,2,3,...)
  1731.  
  1732.  
  1733.       WWWWhhhhyyyy ddddooooeeeessss ppppaaaassssssssiiiinnnngggg aaaa ssssuuuubbbbrrrroooouuuuttttiiiinnnneeee    aaaannnn uuuunnnnddddeeeeffffiiiinnnneeeedddd eeeelllleeeemmmmeeeennnntttt iiiinnnn    aaaa hhhhaaaasssshhhh
  1734.       ccccrrrreeeeaaaatttteeee iiiitttt????
  1735.  
  1736.       If you say something like:
  1737.  
  1738.           somefunc($hash{"nonesuch key here"});
  1739.  
  1740.       Then that element "autovivifies"; that is, it    springs    into
  1741.       existence whether you    store something    there or not.  That's
  1742.       because functions get    scalars    passed in by reference.     If
  1743.       _s_o_m_e_f_u_n_c() modifies $_[0], it    has to be ready    to write it
  1744.       back into the    caller's version.
  1745.  
  1746.       This has been    fixed as of perl5.004.
  1747.  
  1748.       Normally, merely accessing a key's value for a nonexistent
  1749.       key does _n_o_t cause that key to be forever there.  This is
  1750.       different than awk's behavior.
  1751.  
  1752.       HHHHoooowwww ccccaaaannnn IIII mmmmaaaakkkkeeee tttthhhheeee PPPPeeeerrrrllll eeeeqqqquuuuiiiivvvvaaaalllleeeennnntttt ooooffff    aaaa CCCC ssssttttrrrruuuuccccttttuuuurrrreeee////CCCC++++++++
  1753.       ccccllllaaaassssssss////hhhhaaaasssshhhh oooorrrr    aaaarrrrrrrraaaayyyy ooooffff hhhhaaaasssshhhheeeessss    oooorrrr aaaarrrrrrrraaaayyyyssss????
  1754.  
  1755.       Use references (documented in    the _p_e_r_l_r_e_f manpage).
  1756.       Examples of complex data structures are given    in the _p_e_r_l_d_s_c
  1757.       manpage and the _p_e_r_l_l_o_l manpage.  Examples of    structures and
  1758.       object-oriented classes are in the _p_e_r_l_t_o_o_t manpage.
  1759.  
  1760.       HHHHoooowwww ccccaaaannnn IIII uuuusssseeee    aaaa rrrreeeeffffeeeerrrreeeennnncccceeee aaaassss aaaa hhhhaaaasssshhhh kkkkeeeeyyyy????
  1761.  
  1762.       You can't do this directly, but you could use    the standard
  1763.       Tie::Refhash module distributed with perl.
  1764.  
  1765.      DDDDaaaattttaaaa:::: MMMMiiiisssscccc
  1766.       HHHHoooowwww ddddoooo IIII hhhhaaaannnnddddlllleeee bbbbiiiinnnnaaaarrrryyyy ddddaaaattttaaaa ccccoooorrrrrrrreeeeccccttttllllyyyy????
  1767.  
  1768.       Perl is binary clean,    so this    shouldn't be a problem.     For
  1769.       example, this    works fine (assuming the files are found):
  1770.  
  1771.           if (`cat /vmunix`    =~ /gzip/) {
  1772.           print    "Your kernel is    GNU-zip    enabled!\n";
  1773.           }
  1774.  
  1775.       On some systems, however, you    have to    play tedious games
  1776.  
  1777.  
  1778.  
  1779.      Page 27                        (printed 10/23/98)
  1780.  
  1781.  
  1782.  
  1783.  
  1784.  
  1785.  
  1786.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  1787.  
  1788.  
  1789.  
  1790.       with "text" versus "binary" files.  See the section on
  1791.       _b_i_n_m_o_d_e in the _p_e_r_l_f_u_n_c manpage.
  1792.  
  1793.       If you're concerned about 8-bit ASCII    data, then see the
  1794.       _p_e_r_l_l_o_c_a_l_e manpage.
  1795.  
  1796.       If you want to deal with multibyte characters, however,
  1797.       there    are some gotchas.  See the section on Regular
  1798.       Expressions.
  1799.  
  1800.       HHHHoooowwww ddddoooo IIII ddddeeeetttteeeerrrrmmmmiiiinnnneeee wwwwhhhheeeetttthhhheeeerrrr aaaa ssssccccaaaallllaaaarrrr iiiissss aaaa
  1801.       nnnnuuuummmmbbbbeeeerrrr////wwwwhhhhoooolllleeee////iiiinnnntttteeeeggggeeeerrrr////ffffllllooooaaaatttt????
  1802.  
  1803.       Assuming that    you don't care about IEEE notations like "NaN"
  1804.       or "Infinity", you probably just want    to use a regular
  1805.       expression.
  1806.  
  1807.          warn "has nondigits"     if    /\D/;
  1808.           warn "not    a natural number" unless /^\d+$/;          #    rejects    -3
  1809.           warn "not    an integer"      unless /^-?\d+$/;          #    rejects    +3
  1810.          warn "not an integer"     unless    /^[+-]?\d+$/;
  1811.          warn "not a decimal number" unless    /^-?\d+\.?\d*$/;  # rejects .2
  1812.          warn "not a decimal number" unless    /^-?(?:\d+(?:\.\d*)?|\.\d+)$/;
  1813.          warn "not a C float"
  1814.          unless    /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/;
  1815.  
  1816.       If you're on a POSIX system, Perl's supports the
  1817.       POSIX::strtod    function.  Its semantics are somewhat
  1818.       cumbersome, so here's    a getnum wrapper function for more
  1819.       convenient access.  This function takes a string and returns
  1820.       the number it    found, or undef    for input that isn't a C
  1821.       float.  The is_numeric function is a front end to getnum if
  1822.       you just want    to say,    ``Is this a float?''
  1823.  
  1824.           sub getnum {
  1825.           use POSIX qw(strtod);
  1826.           my $str = shift;
  1827.           $str =~ s/^\s+//;
  1828.           $str =~ s/\s+$//;
  1829.           $! = 0;
  1830.           my($num, $unparsed) =    strtod($str);
  1831.           if (($str eq '') || ($unparsed != 0) || $!) {
  1832.               return undef;
  1833.           } else {
  1834.               return $num;
  1835.           }
  1836.           }
  1837.  
  1838.           sub is_numeric { defined &getnum }
  1839.  
  1840.       Or you could check out http://www.perl.com/CPAN/modules/by-
  1841.       module/String/String-Scanf-1.1.tar.gz    instead.  The POSIX
  1842.  
  1843.  
  1844.  
  1845.      Page 28                        (printed 10/23/98)
  1846.  
  1847.  
  1848.  
  1849.  
  1850.  
  1851.  
  1852.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  1853.  
  1854.  
  1855.  
  1856.       module (part of the standard Perl distribution) provides the
  1857.       strtol and strtod for    converting strings to double and
  1858.       longs, respectively.
  1859.  
  1860.       HHHHoooowwww ddddoooo IIII kkkkeeeeeeeepppp    ppppeeeerrrrssssiiiisssstttteeeennnntttt ddddaaaattttaaaa    aaaaccccrrrroooossssssss pppprrrrooooggggrrrraaaammmm ccccaaaallllllllssss????
  1861.  
  1862.       For some specific applications, you can use one of the DBM
  1863.       modules.  See    the _A_n_y_D_B_M__F_i_l_e    manpage.  More generically,
  1864.       you should consult the FreezeThaw, Storable, or Class::Eroot
  1865.       modules from CPAN.
  1866.  
  1867.       HHHHoooowwww ddddoooo IIII pppprrrriiiinnnntttt oooouuuutttt oooorrrr    ccccooooppppyyyy aaaa rrrreeeeccccuuuurrrrssssiiiivvvveeee ddddaaaattttaaaa ssssttttrrrruuuuccccttttuuuurrrreeee????
  1868.  
  1869.       The Data::Dumper module on CPAN is nice for printing out
  1870.       data structures, and FreezeThaw for copying them.  For
  1871.       example:
  1872.  
  1873.           use FreezeThaw qw(freeze thaw);
  1874.           $new = thaw freeze $old;
  1875.  
  1876.       Where    $old can be (a reference to) any kind of data
  1877.       structure you'd like.     It will be deeply copied.
  1878.  
  1879.       HHHHoooowwww ddddoooo IIII ddddeeeeffffiiiinnnneeee mmmmeeeetttthhhhooooddddssss ffffoooorrrr eeeevvvveeeerrrryyyy ccccllllaaaassssssss////oooobbbbjjjjeeeecccctttt????
  1880.  
  1881.       Use the UNIVERSAL class (see the _U_N_I_V_E_R_S_A_L manpage).
  1882.  
  1883.       HHHHoooowwww ddddoooo IIII vvvveeeerrrriiiiffffyyyy aaaa ccccrrrreeeeddddiiiitttt ccccaaaarrrrdddd    cccchhhheeeecccckkkkssssuuuummmm????
  1884.  
  1885.       Get the Business::CreditCard module from CPAN.
  1886.  
  1887.      AAAAUUUUTTTTHHHHOOOORRRR AAAANNNNDDDD    CCCCOOOOPPPPYYYYRRRRIIIIGGGGHHHHTTTT
  1888.       Copyright (c)    1997, 1998 Tom Christiansen and    Nathan
  1889.       Torkington.  All rights reserved.
  1890.  
  1891.       When included    as part    of the Standard    Version    of Perl, or as
  1892.       part of its complete documentation whether printed or
  1893.       otherwise, this work may be distributed only under the terms
  1894.       of Perl's Artistic License.  Any distribution    of this    file
  1895.       or derivatives thereof _o_u_t_s_i_d_e of that package require that
  1896.       special arrangements be made with copyright holder.
  1897.  
  1898.       Irrespective of its distribution, all    code examples in this
  1899.       file are hereby placed into the public domain.  You are
  1900.       permitted and    encouraged to use this code in your own
  1901.       programs for fun or for profit as you    see fit.  A simple
  1902.       comment in the code giving credit would be courteous but is
  1903.       not required.
  1904.  
  1905.  
  1906.  
  1907.  
  1908.  
  1909.  
  1910.  
  1911.      Page 29                        (printed 10/23/98)
  1912.  
  1913.  
  1914.  
  1915.  
  1916.  
  1917.  
  1918.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))      5555////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ4444((((1111))))
  1919.  
  1920.  
  1921.  
  1922.  
  1923.  
  1924.  
  1925.  
  1926.  
  1927.  
  1928.  
  1929.  
  1930.  
  1931.  
  1932.  
  1933.  
  1934.  
  1935.  
  1936.  
  1937.  
  1938.  
  1939.  
  1940.  
  1941.  
  1942.  
  1943.  
  1944.  
  1945.  
  1946.  
  1947.  
  1948.  
  1949.  
  1950.  
  1951.  
  1952.  
  1953.  
  1954.  
  1955.  
  1956.  
  1957.  
  1958.  
  1959.  
  1960.  
  1961.  
  1962.  
  1963.  
  1964.  
  1965.  
  1966.  
  1967.  
  1968.  
  1969.  
  1970.  
  1971.  
  1972.  
  1973.  
  1974.      Page 30                        (printed 10/23/98)
  1975.  
  1976.  
  1977.  
  1978.  
  1979.  
  1980.  
  1981.